package com.pig4cloud.pigx.system.mq;

import com.pig4cloud.pigx.common.customize.exception.MqNotAckException;
import com.pig4cloud.pigx.system.constant.SystemMqConstant;
import com.pig4cloud.pigx.system.entity.SystemLog;
import com.pig4cloud.pigx.system.enums.SystemLogEnum;
import com.pig4cloud.pigx.system.mapper.SystemLogMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 系统日志监听器
 *
 * @since 2022/12/12 15:37
 */
@Component
@RequiredArgsConstructor
public class SystemLogListener {

    private final SystemLogMapper systemLogMapper;

    /**
     * 保存系统日志
     *
     * @param log 日志数据
     * @since 2022/12/12 15:38
     */
    @RabbitListener(queues = SystemMqConstant.QUEUE_FANOUT_SYSTEM_LOG)
    public void run(SystemLog log) {
        // 如果是系统操作
        if (Objects.equals(SystemLogEnum.OperatorType.SYSTEM.getValue(), log.getOperatorType())) {
            Long userId = 0L;
            String username = "系统";
            log.setCreateBy(userId);
            log.setCreateName(username);
            log.setUpdateBy(userId);
            log.setUpdateName(username);
        }

        if (systemLogMapper.insert(log) != 1) {
            throw new MqNotAckException("保存日志数据失败");
        }
    }
}
